<?php
/**
 * Created by PhpStorm.
 * User: lz
 * Date: 2017/8/17
 * Time: 18:10
 */

namespace app\modules\weixin\controllers;

use app\common\components\BaseWebController;
use app\common\service\UrlService;
use app\models\book\Book;
use app\models\market\MarketQrcode;
use app\models\market\QrcodeScanHistory;
use yii\log\FileTarget;

class MsgController extends BaseWebController
{
    public function actionIndex()
    {
        if (!$this->checkSignature()) {
            return "error";
        }

        /**获取用户输入微信公众平台的文字信息*/
        $xml_data = file_get_contents("php://input");

        $this->record_log("[xml_dat]" . $xml_data);

        if (!$xml_data) {
            return "error xml--";
        }

        $xml_obj = simplexml_load_string($xml_data, "SimpleXMLElement", LIBXML_NOCDATA);

        $from_username = $xml_obj->FromUserName;
        $to_username = $xml_obj->ToUserName;
        $msg_type = $xml_obj->MsgType;

        $res = ["type" => "text", "data" => $this->defaultTip()];
        switch ($msg_type) {
            case "text";
                $kw = trim($xml_obj->Content);
                $res = $this->search($kw);
                break;
            case "event":
                $res = $this->parseEvent($xml_obj);
                break;
            default:
                break;
        }

        switch ($res["type"]) {
            case "text";
                return $this->textTpl($from_username, $to_username, $res["data"]);
                break;
            case "rich";
                return $this->richTpl($from_username, $to_username, $res["data"]);
                break;
        }
//
        return $this->get("echostr");
//        return "helloword";
    }

    /**接入微信验证
     * @return bool
     */
    public function checkSignature()
    {
        $signature = trim($this->get("signature", ""));
        $timestamp = trim($this->get("timestamp", ""));
        $nonce = trim($this->get("nonce", ""));

        $tempArr = array(\Yii::$app->params['weixin']['token'], $timestamp, $nonce);

        sort($tempArr);
        $tempStr = implode($tempArr);
        $tempStr = sha1($tempStr);

        if ($tempStr != $signature) {
            return false;
        } else {
            return true;
        }
    }


    /**搜索用户输入的关键字 返回相应的内容
     * @param $kw
     */
    private function search($kw)
    {
        $query = Book::find()->where(['status' => 1]);
        $where_name = ['LIKE', 'name', '%' . $kw . '%', false];
        $where_tag = ['LIKE', 'tags', '%' . $kw . '%', false];
        $query->andWhere(['or', $where_name, $where_tag]);
        $res = $query->orderBy(['id' => SORT_DESC])->limit(3)->all();

        $data = $res ? $this->getRichXml($res) : $this->defaultTip();
        $type = $res ? "rich" : "text";

        return ["type" => $type, "data" => $data];

    }

    /**回復文字消息
     * @param $from_user
     * @param $to_username
     * @param $data
     * @return string
     */
    private function textTpl($from_username, $to_username, $data)
    {

        $tpl = <<<EOT
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>
EOT;
        $RES = sprintf($tpl, $from_username, $to_username, time(), "text", $data);
        return $RES;
    }

    /**回复图文消息
     * @param $from_user
     * @param $to_username
     * @param $data
     * @return string
     */
    private function richTpl($from_username, $to_username, $data)
    {
        $tpl = <<<EOT
        <xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[news]]></MsgType>
        %s
        </xml>
EOT;
        return sprintf($tpl, $from_username, $to_username, time(), $data);

    }

    private function getRichXml($list)
    {
        $article_count = count($list);
        $article_content = "";
        foreach ($list as $_item) {
            $tmp_description = mb_substr(strip_tags($_item['summary']), 0, 20, "utf-8");
            $tmp_pic_url = UrlService::buildPicUrl("book", $_item['main_image']);
            $tmp_url = UrlService::buildCustomerUrl("/product/info", ['id' => $_item['id']]);
            $article_content .= "
            <item>
            <Title><![CDATA[{$_item['name']}]]></Title>
            <Description><![CDATA[{$tmp_description}]]></Description>
            <PicUrl><![CDATA[{$tmp_pic_url}]]></PicUrl>
            <Url><![CDATA[{$tmp_url}]]></Url>
            </item>";
        }

        $article_body = "<ArticleCount>%s</ArticleCount>
        <Articles>
        %s
        </Articles>";
        return sprintf($article_body, $article_count, $article_content);
    }

    /**
     * 默认回复语
     */
    private function defaultTip()
    {
        $resData = <<<EOT
没找到你想要的东西（：\n
EOT;
        return $resData;
    }

    private function parseEvent($dataObj)
    {
        $resType = "text";
        $resData = $this->defaultTip();
        $event = $dataObj->Event;
        switch ($event) {
            case "subscribe":

                $resData = $this->subscribeTips();
                $event_key = $dataObj->EventKey;

                if ($event_key) {
                    $qrcode_key = str_replace("qrscene_", "", $event_key);
                    $qrcode_info = MarketQrcode::findOne(['id' => $qrcode_key]);

                    if ($qrcode_info) {
                        $qrcode_info->total_scan_count += 1;
                        $qrcode_info->updated_time = date("Y-m-d H:i:s");
                        $qrcode_info->update(0);

                        $model_scan_history = new QrcodeScanHistory();
                        $model_scan_history->openid = $dataObj->FromUserName;
                        $model_scan_history->qrcode_id = $qrcode_info['id'];
                        $model_scan_history->created_time = date("Y-m-d H:i:s");

                        $model_scan_history->save(0);
                    }
                }
                break;
            case "CLICK"://自定义菜单点击类型是CLICK的，可以回复指定内容
                $eventKey = trim($dataObj->EventKey);
                switch ($eventKey) {
                }
                break;
        }
        return ['type' => $resType, 'data' => $resData];
    }

    /**
     * 关注默认提示
     */
    private function subscribeTips()
    {
        $resData = <<<EOT
感谢您关注宝丽汽车服务公众号
输入关键字,可以搜索商品哦~~
EOT;
        return $resData;
    }

    public function record_log($msg)
    {
        $log = new FileTarget();
        $log->logFile = \Yii::$app->getRuntimePath() . "/logs/weixin_msg_" . date("Ymd") . ".log";
        $request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
        $log->messages[] = [
            "[url:{$request_uri}][post:" . http_build_query($_POST) . "] [msg:{$msg}]",
            1,
            'application',
            microtime(true)
        ];
        $log->export();
    }

}